<template>
  <div class="screen-recorder">
    <div class="tool-header">
      <h3>🎥 录屏工具</h3>
      <p>支持全屏录制、区域录制、音频录制等功能</p>
    </div>

    <div class="recorder-sections">
      <!-- 录制模式选择 -->
      <div class="section">
        <h4>📹 录制模式</h4>
        <div class="mode-tabs">
          <button 
            v-for="mode in recordModes" 
            :key="mode.id"
            @click="currentMode = mode.id"
            :class="['tab-btn', { active: currentMode === mode.id }]"
          >
            {{ mode.icon }} {{ mode.name }}
          </button>
        </div>
      </div>

      <!-- 录制设置 -->
      <div class="section">
        <h4>⚙️ 录制设置</h4>
        
        <!-- 视频设置 -->
        <div class="settings-group">
          <h5>视频设置</h5>
          <div class="param-group">
            <label>视频质量:</label>
            <select v-model="settings.videoQuality">
              <option value="1080p">1080p (1920x1080)</option>
              <option value="720p">720p (1280x720)</option>
              <option value="480p">480p (854x480)</option>
              <option value="360p">360p (640x360)</option>
            </select>
          </div>
          <div class="param-group">
            <label>帧率 (FPS):</label>
            <select v-model="settings.frameRate">
              <option value="60">60 FPS</option>
              <option value="30">30 FPS</option>
              <option value="24">24 FPS</option>
              <option value="15">15 FPS</option>
            </select>
          </div>
          <div class="param-group">
            <label>视频格式:</label>
            <select v-model="settings.videoFormat">
              <option value="mp4">MP4</option>
              <option value="webm">WebM</option>
              <option value="avi">AVI</option>
            </select>
          </div>
        </div>

        <!-- 音频设置 -->
        <div class="settings-group">
          <h5>音频设置</h5>
          <div class="param-group">
            <label>
              <input type="checkbox" v-model="settings.recordAudio">
              录制系统音频
            </label>
          </div>
          <div class="param-group">
            <label>
              <input type="checkbox" v-model="settings.recordMicrophone">
              录制麦克风
            </label>
          </div>
          <div v-if="settings.recordAudio || settings.recordMicrophone" class="param-group">
            <label>音频质量:</label>
            <select v-model="settings.audioQuality">
              <option value="high">高质量 (320 kbps)</option>
              <option value="medium">中等质量 (192 kbps)</option>
              <option value="low">低质量 (128 kbps)</option>
            </select>
          </div>
        </div>

        <!-- 区域录制设置 -->
        <div v-if="currentMode === 'region'" class="settings-group">
          <h5>录制区域</h5>
          <div class="region-controls">
            <button @click="selectRegion" class="region-btn">
              {{ selectedRegion ? '重新选择区域' : '选择录制区域' }}
            </button>
            <div v-if="selectedRegion" class="region-info">
              <p>区域: {{ selectedRegion.width }}x{{ selectedRegion.height }}</p>
              <p>位置: ({{ selectedRegion.x }}, {{ selectedRegion.y }})</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 输出设置 -->
      <div class="section">
        <h4>📤 输出设置</h4>
        <div class="param-group">
          <label>输出文件名:</label>
          <input v-model="outputFileName" type="text" placeholder="自动生成">
        </div>
        <div class="param-group">
          <label>输出目录:</label>
          <div class="output-dir">
            <input v-model="outputDir" type="text" placeholder="选择输出目录" readonly>
            <button @click="selectOutputDir" class="dir-btn">选择目录</button>
          </div>
        </div>
      </div>



      <!-- 录制控制 -->
      <div class="section">
        <div class="record-controls">
          <button 
            v-if="!isRecording && !isPaused"
            @click="startRecording" 
            :disabled="false"
            class="record-btn start"
          >
            🔴 开始录制
          </button>
          
          <button 
            v-if="isRecording && !isPaused"
            @click="pauseRecording"
            class="record-btn pause"
          >
            ⏸️ 暂停录制
          </button>
          
          <button 
            v-if="isPaused"
            @click="resumeRecording"
            class="record-btn resume"
          >
            ▶️ 继续录制
          </button>
          
          <button 
            v-if="isRecording || isPaused"
            @click="stopRecording"
            class="record-btn stop"
          >
            ⏹️ 停止录制
          </button>
        </div>
      </div>

      <!-- 录制状态 -->
      <div v-if="isRecording || isPaused" class="section">
        <h4>📊 录制状态</h4>
        <div class="status-info">
          <div class="status-item">
            <span class="status-label">状态:</span>
            <span :class="['status-value', statusClass]">
              {{ statusText }}
            </span>
          </div>
          <div class="status-item">
            <span class="status-label">录制时间:</span>
            <span class="status-value time">{{ formatTime(recordingTime) }}</span>
          </div>
          <div class="status-item">
            <span class="status-label">文件大小:</span>
            <span class="status-value">{{ formatFileSize(estimatedSize) }}</span>
          </div>
        </div>
      </div>

      <!-- 录制结果 -->
      <div v-if="recordingResult" class="section">
        <h4>✅ 录制完成</h4>
        <div class="result-info">
          <p><strong>输出文件:</strong> {{ recordingResult.filePath }}</p>
          <p><strong>录制时长:</strong> {{ formatTime(recordingResult.duration) }}</p>
          <p><strong>文件大小:</strong> {{ formatFileSize(recordingResult.fileSize) }}</p>
          <p><strong>分辨率:</strong> {{ recordingResult.resolution }}</p>
        </div>
        <div class="result-actions">
          <button @click="openOutputDir" class="open-btn">打开输出目录</button>
          <button @click="playRecording" class="play-btn">播放录制</button>
        </div>
      </div>

      <!-- 错误显示 -->
      <div v-if="error" class="section error-section">
        <h4>❌ 错误信息</h4>
        <div class="error-message">{{ error }}</div>
        <button @click="error = ''" class="clear-error-btn">清除错误</button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { GetScreenInfo, SelectDirectory, OpenDirectory, GetDefaultRecordingPath, SaveRecordingFile, OpenFile } from '../../wailsjs/go/main/App'

// 响应式数据
const currentMode = ref('fullscreen')
const isRecording = ref(false)
const isPaused = ref(false)
const recordingTime = ref(0)
const estimatedSize = ref(0)
const selectedRegion = ref<any>(null)
const outputFileName = ref('')
const outputDir = ref('')
const recordingResult = ref<any>(null)
const error = ref('')
const mediaRecorder = ref<MediaRecorder | null>(null)
const recordedChunks = ref<Blob[]>([])
const recordingTimer = ref<number | null>(null)



// 录制模式
const recordModes = [
  { id: 'fullscreen', name: '全屏录制', icon: '🖥️' },
  { id: 'window', name: '窗口录制', icon: '🪟' },
  { id: 'region', name: '区域录制', icon: '📐' }
]

// 录制设置
const settings = ref({
  videoQuality: '1080p',
  frameRate: '30',
  videoFormat: 'mp4',
  recordAudio: true,
  recordMicrophone: false,
  audioQuality: 'medium'
})

// 计算属性
const canStartRecording = computed(() => {
  return currentMode.value === 'fullscreen' || 
         currentMode.value === 'window' || 
         (currentMode.value === 'region' && selectedRegion.value)
})

const statusClass = computed(() => {
  if (isRecording.value) return 'recording'
  if (isPaused.value) return 'paused'
  return 'stopped'
})

const statusText = computed(() => {
  if (isRecording.value) return '🔴 录制中'
  if (isPaused.value) return '⏸️ 已暂停'
  return '⏹️ 已停止'
})

// 选择录制区域
function selectRegion() {
  // 这里需要实现区域选择功能
  // 可以通过调用Go后端的屏幕截图和区域选择功能
  selectedRegion.value = {
    x: 100,
    y: 100,
    width: 800,
    height: 600
  }
}

// 选择输出目录
async function selectOutputDir() {
  try {
    const selectedDir = await SelectDirectory()
    if (selectedDir) {
      outputDir.value = selectedDir
    }
  } catch (err) {
    console.error('选择目录失败:', err)
  }
}

// 生成输出文件名
function generateOutputFileName() {
  const now = new Date()
  const timestamp = now.toISOString().replace(/[:.]/g, '-').slice(0, -5)
  outputFileName.value = `screen_recording_${timestamp}.${settings.value.videoFormat}`
}

// 开始录制
async function startRecording() {
  try {
    error.value = ''
    
    // 生成文件名
    if (!outputFileName.value) {
      generateOutputFileName()
    }
    
    // 获取屏幕录制权限
    let stream: MediaStream
    
    // 统一使用getDisplayMedia，让用户选择录制内容
    const displayMediaOptions = {
      video: {
        mediaSource: currentMode.value === 'fullscreen' ? 'screen' : 'window',
        width: { ideal: getResolution().width },
        height: { ideal: getResolution().height },
        frameRate: { ideal: parseInt(settings.value.frameRate) }
      },
      audio: settings.value.recordAudio
    }
    
    stream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions)
    
    // 如果需要录制麦克风，合并音频流
    if (settings.value.recordMicrophone) {
      const micStream = await navigator.mediaDevices.getUserMedia({ audio: true })
      // 这里需要合并音频流的逻辑
    }
    
    // 创建MediaRecorder
    const options = {
      mimeType: getMimeType(),
      videoBitsPerSecond: getVideoBitrate()
    }
    
    mediaRecorder.value = new MediaRecorder(stream, options)
    recordedChunks.value = []
    
    mediaRecorder.value.ondataavailable = (event) => {
      if (event.data.size > 0) {
        recordedChunks.value.push(event.data)
        estimatedSize.value += event.data.size
      }
    }
    
    mediaRecorder.value.onstop = () => {
      saveRecording()
    }
    
    // 开始录制
    mediaRecorder.value.start(1000) // 每秒收集一次数据
    isRecording.value = true
    recordingTime.value = 0
    estimatedSize.value = 0
    
    // 启动计时器
    startTimer()
    
    // 最小化窗口避免录制到应用程序本身
    setTimeout(() => {
      if ((window as any).runtime && (window as any).runtime.WindowMinimise) {
        (window as any).runtime.WindowMinimise()
      }
    }, 500) // 延迟500ms确保录制已开始
    
  } catch (err) {
    error.value = `录制启动失败: ${err}`
  }
}

// 暂停录制
function pauseRecording() {
  if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
    mediaRecorder.value.pause()
    isPaused.value = true
    isRecording.value = false
    stopTimer()
  }
}

// 继续录制
function resumeRecording() {
  if (mediaRecorder.value && mediaRecorder.value.state === 'paused') {
    mediaRecorder.value.resume()
    isPaused.value = false
    isRecording.value = true
    startTimer()
  }
}

// 停止录制
function stopRecording() {
  if (mediaRecorder.value) {
    mediaRecorder.value.stop()
    isRecording.value = false
    isPaused.value = false
    stopTimer()
    
    // 停止所有轨道
    mediaRecorder.value.stream.getTracks().forEach(track => track.stop())
  }
}

// 保存录制
async function saveRecording() {
  if (recordedChunks.value.length === 0) {
    error.value = '没有录制数据'
    return
  }
  
  try {
    const blob = new Blob(recordedChunks.value, { type: getMimeType() })
    
    // 将Blob转换为ArrayBuffer
     const arrayBuffer = await blob.arrayBuffer()
     const uint8Array = new Uint8Array(arrayBuffer)
     
     // 调用后端API保存文件
     const result = await SaveRecordingFile(Array.from(uint8Array), outputFileName.value, outputDir.value)
     
     if (result.success) {
       // 设置结果
       recordingResult.value = {
         filePath: result.filePath,
         duration: recordingTime.value,
         fileSize: blob.size,
         resolution: `${getResolution().width}x${getResolution().height}`
       }
     } else {
       error.value = `保存文件失败: ${result.message}`
     }
  } catch (err) {
    error.value = `保存录制文件失败: ${err}`
  }
}

// 计时器相关
function startTimer() {
  recordingTimer.value = window.setInterval(() => {
    recordingTime.value++
  }, 1000)
}

function stopTimer() {
  if (recordingTimer.value) {
    clearInterval(recordingTimer.value)
    recordingTimer.value = null
  }
}

// 工具函数
function getResolution() {
  const resolutions = {
    '1080p': { width: 1920, height: 1080 },
    '720p': { width: 1280, height: 720 },
    '480p': { width: 854, height: 480 },
    '360p': { width: 640, height: 360 }
  }
  return resolutions[settings.value.videoQuality as keyof typeof resolutions]
}

function getMimeType() {
  const formats = {
    'mp4': 'video/mp4',
    'webm': 'video/webm',
    'avi': 'video/x-msvideo'
  }
  return formats[settings.value.videoFormat as keyof typeof formats] || 'video/webm'
}

function getVideoBitrate() {
  const bitrates = {
    '1080p': 5000000,
    '720p': 2500000,
    '480p': 1000000,
    '360p': 500000
  }
  return bitrates[settings.value.videoQuality as keyof typeof bitrates]
}

function formatTime(seconds: number): string {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 打开输出目录
async function openOutputDir() {
  try {
    await OpenDirectory(outputDir.value)
  } catch (err) {
    console.error('打开目录失败:', err)
  }
}



// 播放录制
async function playRecording() {
  if (!recordingResult.value || !recordingResult.value.filePath) {
    error.value = '没有可播放的录制文件'
    return
  }
  
  try {
    // 使用系统默认程序打开视频文件
    await OpenFile(recordingResult.value.filePath)
  } catch (err) {
    console.error('播放录制失败:', err)
    error.value = `播放录制失败: ${err}`
  }
}

// 组件挂载时的初始化
onMounted(async () => {
  try {
    // 获取默认录制路径
    const defaultPath = await GetDefaultRecordingPath()
    outputDir.value = defaultPath
    
    // 获取屏幕信息
    const screens = await GetScreenInfo()
    console.log('屏幕信息:', screens)
    
    generateOutputFileName()
  } catch (err) {
    console.error('初始化失败:', err)
    outputDir.value = 'C:\\Users\\Public\\Videos\\ScreenRecordings'
    generateOutputFileName()
  }
})

onUnmounted(() => {
  if (isRecording.value || isPaused.value) {
    stopRecording()
  }
  stopTimer()
})
</script>

<style scoped>
.screen-recorder {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 30px;
}

.tool-header h3 {
  color: #fff;
  font-size: 1.8em;
  margin: 0 0 10px 0;
}

.tool-header p {
  color: #ccc;
  margin: 0;
}

.recorder-sections {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.section {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.section h4 {
  color: #fff;
  margin: 0 0 15px 0;
  font-size: 1.2em;
}

.section h5 {
  color: #fff;
  margin: 15px 0 10px 0;
  font-size: 1em;
}

.mode-tabs {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.tab-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 10px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.tab-btn.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: transparent;
}

.settings-group {
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
}

.param-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
  margin-bottom: 15px;
}

.param-group label {
  color: #fff;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.param-group input[type="checkbox"] {
  margin: 0;
}

.param-group input,
.param-group select {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
}

.param-group input:focus,
.param-group select:focus {
  outline: none;
  border-color: #667eea;
}

.region-controls {
  text-align: center;
}

.region-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: transform 0.2s;
}

.region-btn:hover {
  transform: translateY(-2px);
}

.region-info {
  margin-top: 15px;
  text-align: left;
  background: rgba(0, 0, 0, 0.3);
  padding: 15px;
  border-radius: 8px;
}

.region-info p {
  color: #fff;
  margin: 5px 0;
}

.output-dir {
  display: flex;
  gap: 10px;
}

.output-dir input {
  flex: 1;
}

.dir-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.dir-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.record-controls {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.record-btn {
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s;
  min-width: 120px;
}

.record-btn.start {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  color: white;
}

.record-btn.pause {
  background: linear-gradient(135deg, #feca57 0%, #ff9ff3 100%);
  color: white;
}

.record-btn.resume {
  background: linear-gradient(135deg, #48dbfb 0%, #0abde3 100%);
  color: white;
}

.record-btn.stop {
  background: linear-gradient(135deg, #54a0ff 0%, #2e86de 100%);
  color: white;
}

.record-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.record-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.status-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 6px;
}

.status-label {
  color: #ccc;
  font-weight: 500;
}

.status-value {
  color: #fff;
  font-weight: 600;
}

.status-value.recording {
  color: #ff6b6b;
  animation: pulse 1s infinite;
}

.status-value.paused {
  color: #feca57;
}

.status-value.time {
  font-family: 'Courier New', monospace;
  font-size: 1.1em;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.result-info p {
  color: #fff;
  margin: 8px 0;
}

.result-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.open-btn, .play-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.2s;
}

.open-btn:hover, .play-btn:hover {
  transform: translateY(-2px);
}

.error-section {
  border-color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
}

.error-message {
  color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 10px;
}

.clear-error-btn {
  background: #ff6b6b;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
}



@media (max-width: 768px) {
  .mode-tabs {
    flex-direction: column;
  }
  
  .record-controls {
    flex-direction: column;
  }
  
  .output-dir {
    flex-direction: column;
  }
  
  .result-actions {
    flex-direction: column;
  }
}
</style>